Unlocking the Power of ServiceNow: A Deep Dive into the `sys_user` Table and User Management
Ever wondered where all the magic happens when it comes to who can do what in ServiceNow? Or how that new hire gets access to their critical applications? It all starts with the foundational sys_user table. In the world of ServiceNow, effective user management isn’t just about creating accounts; it’s about building a secure, efficient, and scalable environment that empowers your workforce while protecting your sensitive data.
This article will take you on a journey through the heart of ServiceNow’s user and group management, exploring the crucial tables, best practices, scripting techniques, and advanced concepts that every ServiceNow administrator, developer, and even aspiring professional needs to master. Whether you’re setting up a new department, troubleshooting access issues, or preparing for your next interview, understanding the sys_user table and its ecosystem is non-negotiable.
The Heart of Identity: Understanding the sys_user Table
At its core, ServiceNow is all about managing workflows and data for people. And the central repository for all those people? You guessed it: the sys_user table. Think of it as the master directory for everyone who interacts with your ServiceNow instance, from end-users requesting services to administrators configuring the platform.
While sys_user holds the individual details like usernames, names, emails, and active status, it doesn’t work in isolation. To truly build a robust access model, we rely on a constellation of related tables that define groups, roles, and memberships. Let’s get acquainted with these critical companions:
-
sys_user: The user table itself. This is where individual user records reside. -
sys_user_group: The group table. Organizations use groups to logically categorize users, often by department, function, or project. -
sys_user_grmember: The group member table. This is the crucial link that associates a specific user with a specific group. It defines who belongs to which team. -
sys_user_has_role: The user has role table. This table directly assigns a role to an individual user. While possible, we’ll soon discuss why this isn’t always the best practice. -
sys_group_has_role: The group has role table. This table assigns a role to an entire group. This is often the preferred method for managing permissions.
Understanding these tables is fundamental. It’s like knowing the blueprint of your house – you can’t build or maintain it effectively without it.
User and Group Management: Your Daily Toolkit
Whether you’re onboarding new employees, restructuring departments, or fine-tuning access, you’ll constantly be interacting with users and groups. Let’s explore how to manage them, both through the intuitive UI and with the powerful flexibility of scripting.
Creating Users: Manually vs. Scripting Power
Most new users are provisioned through integrations with identity providers like Active Directory or Okta, but sometimes you need to create a user manually or via a script for specific purposes, like service accounts or testing.
Manual User Creation
Navigating to System Security > Users and clicking “New” allows you to fill in all the details for a new user. This is straightforward for individual cases.
Scripted User Creation
For bulk user creation, system integrations, or automated provisioning within a workflow, scripting is your friend. We leverage GlideRecord, ServiceNow’s API for database interactions.
var userGr = new GlideRecord('sys_user');
userGr.initialize(); // Prepares a new record for insertion
userGr.username = 'jdoe';
userGr.first_name = 'John'; // Corrected field name from original reference
userGr.last_name = 'Doe';
userGr.email = 'jdoe@example.com';
userGr.insert(); // Commits the new record to the database
gs.info('User jdoe created successfully.');
Practical Tip: Always remember to set required fields like username. For production systems, you’d typically include error handling and ensure uniqueness before inserting. Using initialize() is crucial as it sets up a new, empty record.
Crafting Groups: Organizing Your Workforce
Groups are pivotal for managing access, assigning tasks, and facilitating communication. Instead of assigning tasks or roles to individuals, you assign them to groups, making management much simpler.
Manual Group Creation
Navigate to User Administration > Groups and click “New” to create a group through the UI. You can define its name, manager, description, and more.
Scripted Group Creation
Similar to users, groups can be created programmatically using GlideRecord:
var newGr = new GlideRecord('sys_user_group');
newGr.initialize();
newGr.name = 'IT Help Desk'; // Renamed from 'testing' for better example
// For 'manager', you'd typically use the sys_id of an existing user.
// Example: newGr.manager = '62826bf03710200044e0bfc8bcbe5df1';
newGr.email = 'it.helpdesk@example.com';
newGr.description = 'Support team for IT-related issues.';
newGr.insert();
gs.info('Group "IT Help Desk" created successfully.');
Why Groups are Crucial: Groups abstract away individual users from assignments and permissions. If a person leaves or changes roles, you simply adjust their group memberships rather than reassigning every single item or role they had.
Mastering Roles and Permissions: The Security Backbone
Roles are the cornerstone of access control in ServiceNow, dictating what users can see and do. Proper role management is critical for security and compliance.
The Golden Rule: Roles via Groups!
This is perhaps the most important best practice in ServiceNow administration:
Always assign roles to groups, and then assign users to those groups, rather than directly assigning roles to individual users.
Why? It boils down to maintainability, consistency, and efficient offboarding.
- Maintenance: If a role’s permissions change, you update it once on the group, and all members inherit the change. If you assign roles directly, you’d have to find and update every individual user.
- Consistency: All members of a group automatically get the same set of permissions, ensuring uniformity.
- Offboarding: When an employee leaves, simply removing them from their groups automatically revokes all associated roles, preventing lingering access. If roles are directly assigned, you’d need to manually remove each one, a tedious and error-prone process.
Assigning Roles to Groups (Best Practice)
You can assign roles to groups through the UI by navigating to a group record and adding roles in the “Roles” related list. Scripting this involves creating a record in the sys_group_has_role table:
var grpRole = new GlideRecord('sys_group_has_role');
grpRole.initialize();
grpRole.setValue('group', '477a05d153013010b846ddeeff7b1225'); // sys_id of the group (e.g., IT Help Desk)
grpRole.setValue('role', '2831a114c611228501d4ea6c309d626d'); // sys_id of the desired role (e.g., itil)
grpRole.insert();
gs.info('Role assigned to group successfully.');
Assigning Roles to Users (When Necessary, but Beware!)
While generally discouraged, there might be rare exceptions where a user needs a specific role that no group provides, and creating a new group just for that one role/user is overkill. However, proceed with caution! Scripting this involves the sys_user_has_role table:
var userRole = new GlideRecord('sys_user_has_role');
userRole.initialize();
userRole.setValue('user', '62826bf03710200044e0bfc8bcbe5df1'); // sys_id of the user (e.g., jdoe)
userRole.setValue('role', '2831a114c611228501d4ea6c309d626d'); // sys_id of the desired role (e.g., itil)
userRole.insert();
gs.info('Role assigned to user directly. (Consider using groups instead!)');
Interview Relevance: This “best practice” question about assigning roles to groups vs. users is a common interview topic. Be ready to explain the “why.”
The security_admin Role for Access Control
To perform sensitive security tasks, such as creating or modifying Access Control Lists (ACLs), you need the elevated security_admin role. This role acts as a temporary elevated privilege, often requiring re-elevation after a certain period or session logout to ensure strong security governance.
Managing Group Members: Keeping Teams Fluid
As teams evolve, so do their memberships. Adding and removing users from groups is a frequent task.
Adding Group Members
Manually, you navigate to the group record and use the “Group Members” related list. Scripting involves creating a record in the sys_user_grmember table:
var grMem = new GlideRecord('sys_user_grmember'); // Corrected table name from original reference to match actual table name: sys_user_grmember
grMem.initialize();
grMem.user = '62826bf03710200044e0bfc8bcbe5df1'; // sys_id of the user
grMem.group = '477a05d153013010b846ddeeff7b1225'; // sys_id of the group
grMem.insert();
gs.info('User added to group successfully.');
Removing Group Members
To remove a member via script, you query the sys_user_grmember table for the specific user-group relationship and then delete that record:
var grMem = new GlideRecord('sys_user_grmember'); // Corrected table name
grMem.addQuery('user', '62826bf03710200044e0bfc8bcbe5df1'); // sys_id of the user
grMem.addQuery('group', '477a05d153013010b846ddeeff7b1225'); // sys_id of the group
grMem.query();
if (grMem.next()) {
grMem.deleteRecord();
gs.info('User removed from group successfully.');
} else {
gs.info('User was not found in the specified group.');
}
Troubleshooting Tip: Always double-check your sys_IDs when scripting. A common mistake is using the wrong ID, leading to records not being found or created. You can find sys_IDs by right-clicking the header of any record and selecting “Copy sys_id.”
Beyond Basic Management: Advanced User Concepts
ServiceNow offers several specialized user-related features that enhance flexibility and security.
User Delegation: When You Need a Stand-in
User delegation is a lifesaver for business continuity. It allows one user to temporarily act on behalf of another.
What it is: User delegation means granting another user permissions to perform specific tasks normally handled by the delegator. This is most commonly used when a user is unavailable, such as during vacation or extended leave.
Real-World Example: Imagine an approval manager going on a two-week holiday. Without delegation, critical approvals might stall, impacting workflows. By delegating their approval tasks to a colleague, business processes continue smoothly. The delegated user can then approve or reject items just as the original manager would.
How to Set It Up: As an end-user, you can typically set up delegation by navigating to your user profile (e.g., by clicking your name in the header), scrolling down, and selecting the “Delegates” related list. Here you can:
- Specify the Delegate (the person you want to delegate to).
- Set Start Date and End Date for the delegation period.
- Grant specific permissions: for Approvals, Notifications, and sometimes even Assignments (though assignment delegation is less common for standard users and often handled by group assignments).
The Enigmatic “Web Services User”
Not all users interact with ServiceNow through its graphical interface.
What it is: A web services user is a special type of user account specifically configured to grant access to a third-party application or integration to connect to ServiceNow via APIs (Application Programming Interfaces).
Key Characteristic: The most important distinction is that a web services user cannot log in via the standard ServiceNow user interface (UI). Their sole purpose is machine-to-machine communication, usually for data exchange, triggering workflows, or system integrations.
Security Implication: These accounts should be managed with extreme care. They typically have specific roles granting them only the necessary permissions to perform their integration tasks, adhering to the principle of least privilege. Strong password policies and regular audits are essential for web services users.
User Preferences: A Personal Touch
ServiceNow understands that different users have different needs and preferences.
What they are: User preferences allow individual users to customize certain aspects of their ServiceNow experience. These settings are stored in the sys_user_preference table.
Impact: Crucially, a user’s preferences only impact that specific user. They do not affect other users or the global system settings.
Examples: Common user preferences include:
- Time zone setting
- Display density (comfortable, cozy, compact)
- List layout configurations (which columns are shown, their order)
- Notifications settings (e.g., email vs. push notifications)
- Theme selection
This allows for a personalized and more efficient workspace for each individual.
Impersonation: Stepping into Another’s Shoes (for Testing!)
When developing or troubleshooting, you often need to see ServiceNow exactly as another user would.
What it is: Impersonation is the act of temporarily logging in as another user for testing, debugging, or validation purposes. When you impersonate a user, you temporarily gain their exact view and access rights within the instance.
Purpose:
- Testing: Verify if a new feature, UI policy, or ACL works correctly for users with specific roles or group memberships.
- Troubleshooting: Replicate an issue reported by a user to understand their experience and diagnose problems more effectively.
- Validation: Ensure that certain information or actions are appropriately restricted or available based on a user’s profile.
To impersonate, an administrator or a user with the user_admin role can click their name in the header and select “Impersonate User.” Remember to “End Impersonation” when done to return to your own session.
Important: Use impersonation responsibly and only for legitimate testing or troubleshooting. All actions performed while impersonating are attributed to the impersonated user in system logs.
Cracking the Code: Accessing User Data in Scripts
In many scripts – client-side UI policies, server-side business rules, or script includes – you’ll need to know details about the currently logged-in user.
Who Am I? Getting Current User Details
The method you use depends on where your script is running:
Client-Side (Browser)
When your script runs in the user’s browser (e.g., Client Scripts, UI Policies), you use the g_user object:
// Get the current logged-in user's sys_id
var userID = g_user.userID;
// Example: '6816f79cc0a8016401c5a33be04be441'
alert('Your user ID is: ' + userID);
g_user also provides other useful properties like g_user.userName, g_user.firstName, g_user.lastName, and g_user.hasRole().
Server-Side (ServiceNow Instance)
When your script runs on the ServiceNow server (e.g., Business Rules, Script Includes, Workflows), you use the gs (GlideSystem) object:
// Get the current logged-in user's sys_id
var userID = gs.getUserID();
// Example: '6816f79cc0a8016401c5a33be04be441'
gs.info('Server-side user ID: ' + userID);
Key Difference: Remember, g_user is for the client (browser), and gs.getUser() / gs.getUserID() is for the server. Mixing them up will lead to errors!
Are They Part of the Team? Checking Group Membership
A very common server-side requirement is to check if the current user belongs to a specific group.
if (gs.getUser().isMemberOf('IT Help Desk')) { // Check if user is a member of 'IT Help Desk' group
gs.info('Current user is a member of the IT Help Desk group.');
// Perform actions specific to IT Help Desk members
} else {
gs.info('Current user is NOT a member of the IT Help Desk group.');
}
This method returns true or false and is incredibly useful for conditionally executing logic, displaying UI elements, or enforcing access rules based on group affiliation.
Relationships and Referrals: Connecting the Dots
Understanding how tables relate to each other and how to filter data in reference fields is crucial for building intuitive and efficient applications.
Table Relationships: Understanding the Architecture
ServiceNow’s relational database structure is based on how records relate to each other.
-
One-to-Many Relationship: Users and Incidents
A single user (from
sys_user) can be associated with multiple incidents (in theincidenttable), for example, as the ‘Caller’ or ‘Assigned To’. However, each individual incident record is typically associated with only one ‘Caller’ user at a time. This is a classic one-to-many. -
Many-to-Many Relationship: Incidents and Groups
An incident can be associated with multiple groups (e.g., an ‘Assignment Group’ and a ‘Watchlist Group’). Conversely, a single group can be associated with multiple incidents. This requires a “many-to-many” relationship, often implemented with an intermediate “junction” table (like
task_m2m_groupfor task-to-group relationships, though the reference implies direct association, it’s typically through specific fields or junction tables in practice).
Why this matters: These relationships dictate how you query and report on data. For example, to find all incidents opened by a specific user, you’d query the incident table, filtering by the ‘caller_id’ field that references the sys_user table.
Reference Qualifiers: Precision in Data Selection
Have you ever seen a dropdown list with hundreds or thousands of options? Reference qualifiers are your tool to bring order to that chaos, ensuring users only see relevant choices.
Purpose: Reference Qualifiers restrict the data displayed in reference fields (like “Assigned To” or “Configuration Item”) and List type fields, helping users find the correct record faster and improving data quality.
There are three main types, each offering increasing levels of flexibility:
1. Simple Reference Qualifier
- Description: The most straightforward type. You define a fixed query string, just like you would in a list filter, to filter the records shown.
- Example: In a reference field pointing to the User table, you might only want to show active users.
-
How to Use:
- Open the dictionary entry for your reference field.
- In the “Reference Qualifier” field, set the condition directly.
Example: active=true^company=javascript:gs.getUser().getCompanyID()(This slightly more advanced simple qualifier would show active users from the current user’s company).
2. Dynamic Reference Qualifier
- Description: This type allows for contextual filtering without writing complex script. It uses a predefined “Dynamic Filter Option” that can adapt based on the current record or other field values.
- Example: Displaying only incidents assigned to the current user’s assignment group, or only active CIs in a specific location.
-
How to Use:
- First, create a Dynamic Filter Option: Navigate to System Definition > Dynamic Filter Options. Define your filter logic there (e.g., “Assigned to my groups”).
- In the reference field dictionary entry, select “Dynamic” for the “Reference Qualifier” type.
- Choose your created Dynamic Filter Option.
3. Advanced Reference Qualifier (JavaScript Reference Qualifier)
- Description: This is the most powerful and flexible type, using custom JavaScript code to build complex, context-aware queries. It allows you to implement almost any filtering logic you can imagine.
- Example: Filtering the “Assigned To” field on an Incident to show only active users who are members of the currently selected “Assignment Group” AND have the ‘itil’ role.
-
How to Use:
- In the reference field dictionary entry, select “Advanced” for the “Reference Qualifier” type.
- Enter JavaScript code that returns a valid encoded query string.
javascript: 'active=true^roles=itil^EQ^group=' + current.assignment_group; // This example assumes 'current.assignment_group' provides the sys_id of the groupTroubleshooting Advanced Qualifiers:
- Syntax Errors: Even a tiny typo can break the qualifier. Test your query string in a list filter first to ensure it’s valid.
-
currentObject: Ensurecurrentis available and contains the data you expect. If the field is on a new record that hasn’t been saved,currentmight not have values. - Performance: Complex JavaScript qualifiers, especially those involving multiple GlideRecord queries, can impact form load times. Optimize your code!
Differences Explained:
- Simple vs. Dynamic: Simple qualifiers are static or rely on basic field comparisons. Dynamic qualifiers offer contextual filtering without code, using pre-built logic from Dynamic Filter Options. Simple is fixed, Dynamic is adaptable (pre-coded).
- Dynamic vs. Advanced: Dynamic is about selecting a pre-configured filter. Advanced is about writing a brand new, custom script to generate the filter on the fly. Advanced gives you ultimate control, while Dynamic is quicker for common, reusable scenarios.
- Simple vs. Advanced: Simple is for basic, often static, filtering with direct query strings. Advanced is for highly complex, conditional, or multi-faceted filtering that requires programmatic logic to construct the query string. Simple is declarative, Advanced is programmatic.
Interview Relevance: Reference Qualifiers are a fundamental topic in ServiceNow interviews. You should be able to explain all three types, provide examples, and discuss their use cases.
Troubleshooting Common sys_user Issues
Even with best practices, user management can present challenges. Here are a few common issues and how to approach them:
-
User Cannot Log In:
- Check `Active` status: Is the user record `active=true`?
- Password: Has the user tried resetting their password? Is there an SSO integration failing?
- Locked Out: Is the `locked_out` field true? An administrator can clear this.
- Roles: Does the user have at least one role (like `snc_internal`) or is a member of a group with a role to access the platform?
-
Roles Not Applying Correctly:
- Group Membership: Is the user actually a member of the correct group(s) that provide the desired roles? Check `sys_user_grmember`.
- Role Inheritance: Are the roles assigned to the group? Is that group part of another group (cascading roles)?
- Role Conflicts: Does another role or ACL override the expected access?
-
Script Errors in User/Group Management:
- Field Names: Double-check field names (e.g., `first_name` vs `firstname`). A common pitfall.
- Sys_IDs: Ensure you’re using correct and valid sys_IDs for users, groups, and roles.
- GlideRecord Lifecycle: Remember `initialize()` for new records, `query()` for existing, and `update()`/`insert()`/`deleteRecord()` to commit changes.
- Context: Is your script running server-side (`gs`) or client-side (`g_user`)?
Interview Corner: What Recruiters Look For
When discussing user management, interviewers often look for a comprehensive understanding beyond just knowing table names. Be prepared to articulate:
- Best Practices: Especially the “roles via groups” principle and its justifications.
- Scripting Fundamentals: How to use GlideRecord for CRUD operations on user and group tables.
- Context-Aware Scripting: When to use `g_user` vs. `gs.getUserID()`.
- Specialized User Types: Explain delegation and web services users clearly.
- Reference Qualifiers: Detail all three types and their differences, providing use cases. This demonstrates your ability to build user-friendly interfaces.
- Security Awareness: Discuss the importance of roles, `security_admin`, and the principle of least privilege.
Conclusion
The sys_user table is more than just a list of names; it’s the anchor of identity and access within your ServiceNow instance. By mastering its related tables, understanding the nuances of role assignment, embracing scripting for efficiency, and leveraging advanced features like delegation and reference qualifiers, you’re not just managing users – you’re building a resilient, secure, and user-friendly platform. So, go forth and manage those users with confidence, knowing you’ve got a solid grasp of the ServiceNow identity landscape!