Microsoft Graph to Jira Assets User Ingestion

Microsoft Graph to Jira Assets User Ingestion

Mihai Perdum
Mihai Perdum
Author

30 min readFebruary 1, 2026

The ingestion system consists of three main components:

  1. Microsoft Graph API Client - Handles OAuth 2.0 authentication and fetches user data including manager information
  2. Jira Cloud Assets Client - Interacts with Jira Service Management Assets API using workspace tokens
  3. Ingestion Engine - Coordinates entire process including user matching, change detection, object lookups, and update logic

The system processes users in a streaming fashion:

  • Fetches users from Microsoft Graph API
  • Matches them against existing assets using multiple criteria
  • Detects changes while preserving existing data
  • Looks up object references (Company, Department, License)
  • Updates or creates users with proper error handling

Key Challenges Addressed

Atlassian's Jira Service Management (JSM) Assets API lacks comprehensive public documentation for certain operations. This implementation provides practical solutions for:

  • Object Reference Attributes (Type 1) - AQL responses return only objectTypeAttributeId, requiring ID-to-name mapping cache
  • User Type Attributes (Type 2) - Microsoft Graph provides email, but Jira Assets requires accountId, requiring separate Jira REST API lookup
  • Business Rule Restrictions - Some object references cannot be used with certain asset types due to schema constraints
  • Partial Update Failures - Attribute-level errors require retry mechanism with alternative object matches
  • Data Preservation - Microsoft Graph is the authority, but should never clear existing valid data

Architecture

Client Initialization

javascript
1class MicrosoftGraphUserIngestion {
2  constructor(options = {}) {
3    this.options = {
4      dryRun: options.dryRun || false,
5      preview: options.preview || false,
6      limit: options.limit || 0,
7      debug: options.debug || false,
8      mappingFile: options.mapping || null,
9      schemaId: options.schemaId || 
10        parseInt(process.env.OBJECT_SCHEMA_ID) || DEFAULT_SCHEMA_ID,
11      objectTypeId: options.objectTypeId || 
12        parseInt(process.env.OBJECT_TYPE_ID) || DEFAULT_OBJECT_TYPE_ID,
13      filter: "userType eq 'Member'"
14    };
15
16    this.stats = {
17      startTime: null,
18      endTime: null,
19      totalUsersFetched: 0,
20      existingUsersMatched: 0,
21      newUsersCreated: 0,
22      existingUsersUpdated: 0,
23      usersSkipped: 0,
24      usersFailed: 0,
25      errors: [],
26    };
27
28    this.graphApiClient = new MicrosoftGraphApiClient(
29      process.env.MS_CLIENT_ID,
30      process.env.MS_TENANT_ID,
31      process.env.MS_CLIENT_SECRET,
32    );
33
34    this.cloudApiClient = new CloudApiClient(
35      process.env.WORKSPACE_ID,
36      process.env.CLOUD_API_TOKEN,
37      process.env.CLOUD_BASE_URL || "https://api.atlassian.com",
38    );
39
40    this.attributeIdToNameMap = new Map();
41    this.attributeIdToTypeInfoMap = new Map();
42    this.existingUsersMap = new Map();
43    
44    this.userObjectCache = new Map();
45    this.departmentObjectCache = new Map();
46    this.licenseObjectCache = new Map();
47    this.companyObjectCache = new Map();
48    this.locationObjectCache = new Map();
49  }
50}

Caching Strategy

Multiple cache maps are implemented for performance and fallback support:

javascript
1// ID-to-name mapping - enables attribute lookups by name
2this.attributeIdToNameMap = new Map();
3this.attributeIdToTypeInfoMap = new Map();
4
5// Object lookup caches - stores ALL potential matches for fallback
6this.companyObjectCache = new Map();
7this.departmentObjectCache = new Map();
8this.licenseObjectCache = new Map();
9this.locationObjectCache = new Map();
10
11// User lookup cache - avoid repeated Jira REST API calls
12this.userObjectCache = new Map();

Understanding Jira Assets Attribute Types

Jira Assets uses three main attribute types that require different handling:

Type 0 (Text/String Attributes)

Simple string values like Name, Email, Title, Location (as text). Direct read/write with string values. No special handling required.

Type 1 (Object Reference Attributes)

References to other Assets objects like Company, Department, License. Most complex to handle!

Problem 1: AQL returns minimal information When querying Assets with AQL, response only includes objectTypeAttributeId and NOT the full attribute object with name field.

Example AQL Response Structure:

json
1{
2  "objectEntries": [
3    {
4      "id": "12345",
5      "objectTypeAttributeId": "1486",
6      "objectAttributeValues": [
7        {
8          "value": "UD-14341",
9          "displayValue": "Example Company Inc."
10        }
11      ]
12    }
13  ]
14}

Note: The objectTypeAttributeId (1486) tells us this is a Company attribute, but we don't know the attribute NAME without additional lookup.

Problem 2: Different values needed for comparison vs. update

  • For COMPARISON: We need displayValue (object name) to match against Microsoft Graph data
  • For UPDATE: We need value (object ID/key) to write to asset

Example Asset State:

json
1{
2  "attributes": [
3    {
4      "objectTypeAttributeId": "1486",
5      "objectAttributeValues": [
6        {
7          "value": "UD-14341",        // This is the ID we write
8          "displayValue": "Example Company Inc."  // This is the name we compare
9        }
10      ]
11    }
12  ]
13}

Type 2 (User Attributes)

References to Jira Platform users by accountId. The challenge:

Problem: Email to AccountId Mapping Microsoft Graph provides email addresses (e.g., user@example.com), but Jira Assets requires accountId (e.g., 70121:abc-123-def) for User type attributes.

Solution: Separate Jira REST API Lookup We need to call Jira REST API to look up user by email and retrieve their accountId.

Solution 1: ID-to-Name Mapping Cache

Since AQL responses only return objectTypeAttributeId, we need to build a cache that maps attribute IDs to their names. This enables us to look up attributes by name instead of ID.

Implementation Code

javascript
1// First, fetch all attributes and build ID-to-name mapping
2const attributes = await this.cloudApiClient.getObjectTypeAttributes(
3  this.options.objectTypeId
4);
5
6this.attributeIdToNameMap = new Map();
7this.attributeIdToTypeInfoMap = new Map();
8
9for (const attr of attributes) {
10  this.attributeIdToNameMap.set(attr.id, attr.name);
11  this.attributeIdToTypeInfoMap.set(attr.id, {
12    name: attr.name,
13    type: attr.type,    // Type codes: 0=Text, 1=Object, 2=User
14  });
15}

Using the Cache

javascript
1getAttributeValue(asset, attributeName) {
2  // Find attribute by ID using ID-to-name mapping
3  const attr = asset.attributes.find((a) => {
4    const attrName = this.attributeIdToNameMap[a.objectTypeAttributeId];
5    return attrName && attrName.toLowerCase() === attributeName.toLowerCase();
6  });
7  
8  if (!attr || !attr.objectAttributeValues || 
9      attr.objectAttributeValues.length === 0) {
10    return "";
11  }
12  
13  return attr.objectAttributeValues[0].value;
14}

Type 1 Attributes - Return DisplayValue for Comparison

For Object Reference attributes, we need to return displayValue instead of value for comparison:

javascript
1getAttributeValue(asset, attributeName) {
2  // Find attribute by ID
3  const attr = asset.attributes.find((a) => {
4    const attrName = this.attributeIdToNameMap[a.objectTypeAttributeId];
5    return attrName && attrName.toLowerCase() === attributeName.toLowerCase();
6  });
7  
8  if (!attr || !attr.objectAttributeValues || 
9      attr.objectAttributeValues.length === 0) {
10    return "";
11  }
12  
13  const attrId = attr.objectTypeAttributeId;
14  const attrTypeInfo = this.attributeIdToTypeInfoMap[attrId];
15  
16  let returnValue = attr.objectAttributeValues[0].value;
17  
18  // For Object References (Type 1), return displayValue for comparison
19  if (attrTypeInfo && attrTypeInfo.type === 1 && 
20      attr.objectAttributeValues[0].displayValue) {
21    returnValue = attr.objectAttributeValues[0].displayValue;
22    // This enables: "Example Company" (from Assets) === "Example Company" (from Graph)
23  }
24  
25  return returnValue;
26}

Why This Matters

Without this fix: Comparison would fail because:

  • Asset value: "UD-14341" (object ID)
  • Graph value: "Example Company" (company name)
  • Result: "UD-14341" !== "Example Company" (incorrect - change detected when shouldn't be!)

With this fix: Comparison works correctly:

  • Asset value: "Example Company" (display name)
  • Graph value: "Example Company" (company name)
  • Result: "Example Company" === "Example Company" (correct - no false change!)

Solution 2: Object Reference Attribute Lookup

For Type 1 attributes like Company, Department, License, we need to look up the object by name and use its ID for updates.

Implementation Code

javascript
1async lookupObjectId(attributeName, value) {
2  if (!value) {
3    return "";
4  }
5
6  // Cache lookup to avoid repeated AQL queries
7  const cacheKey = `${attributeName}:${value}`;
8  
9  // Check if we have cached potential matches
10  if (this.companyObjectCache.has(cacheKey)) {
11    const cachedMatches = this.companyObjectCache.get(cacheKey);
12    
13    // Return first match if cached as array
14    if (Array.isArray(cachedMatches) && cachedMatches.length > 0) {
15      return cachedMatches[0];
16    }
17    
18    // Return single value if cached as string
19    if (typeof cachedMatches === "string") {
20      return cachedMatches;
21    }
22  }
23
24  console.log(`Looking up ${attributeName} object for: ${value}`);
25
26  try {
27    const normalizedAttrName = attributeName.toLowerCase();
28    
29    // Auto-discover Company object type if needed
30    let objectTypeId = null;
31    if (normalizedAttrName === "company" && !process.env.COMPANY_OBJECT_TYPE_ID) {
32      console.log(`Auto-discovering Company object type...`);
33      const schemas = await this.cloudApiClient.getSchemas();
34      for (const schema of schemas) {
35        const objectTypes = await this.cloudApiClient.getObjectTypes(schema.id);
36        const companyType = objectTypes.find(
37          (ot) => ot.name.toLowerCase() === "company"
38        );
39        if (companyType) {
40          objectTypeId = companyType.id;
41          console.log(`Found Company object type: ${companyType.name} (ID: ${objectTypeId})`);
42          break;
43        }
44      }
45    }
46    
47    // Build AQL query to find object by name OR key
48    const escapedValue = this.escapeAQLValue(value);
49    let aqlQuery = `Name = "${escapedValue}" OR Key = "${escapedValue}"`;
50
51    // Add objectType filter for Company/Location/License (not Department)
52    if (objectTypeId && normalizedAttrName !== "department") {
53      aqlQuery += ` AND objectType = ${objectTypeId}`;
54    }
55
56    console.log(`AQL Query: ${aqlQuery}`);
57    
58    // Search for multiple matches (limit 10 instead of 1) to allow validation
59    const response = await this.cloudApiClient.executeAQL(
60      aqlQuery,
61      0,
62      10,
63      true,
64    );
65
66    if (response && (response.objectEntries || response.values)) {
67      const objectEntries = response.objectEntries || response.values;
68      console.log(`Object entries found: ${objectEntries.length}`);
69      
70      if (objectEntries.length > 0) {
71        // CACHE ALL potential matches BEFORE validation for fallback!
72        const allPotentialMatches = objectEntries.map(
73          (obj) => obj.key || obj.objectKey,
74        );
75        
76        this.companyObjectCache.set(cacheKey, allPotentialMatches);
77        
78        // Validate each match and return first valid one
79        for (const object of objectEntries) {
80          if (this.validateObjectMatch(attributeName, value, object)) {
81            const objectKey = object.key || object.objectKey;
82            console.log(`Validated and found ${attributeName}: ${object.label || object.name} (Key: ${objectKey})`);
83            return objectKey;
84          }
85        }
86      }
87    }
88    
89    return ""; // No object found
90  } catch (error) {
91    console.warn(`Error looking up ${attributeName}: ${error.message}`);
92    return "";
93  }
94}

Why This Matters - Business Rule Restrictions

Multiple Company objects might have the same name but different keys due to different schemas or object types:

Object entries found: 2 Match 1: Example Company (Key: UD-14341) Match 2: Example Company (Key: ADI-2952)

Problem: Some Company objects cannot be used with certain User object types due to business rule restrictions.

Solution: Cache ALL potential matches as an array. If the first match fails due to restrictions, we can automatically try the next match!

Solution 3: User Type Attribute Lookup

Jira User attributes reference Jira Platform users by accountId. This requires a separate API call to Jira REST API.

Implementation Code

javascript
1async lookupUserAccountId(email) {
2  // Check cache first to avoid repeated REST API calls
3  if (this.userObjectCache.has(email)) {
4    return this.userObjectCache.get(email);
5  }
6
7  console.log(`Looking up Jira User for email: ${email}`);
8
9  try {
10    // Search for Jira Platform user by email
11    const jiraUser = await this.cloudApiClient.searchJiraUser(email);
12
13    if (jiraUser && jiraUser.accountId) {
14      // Cache the result
15      this.userObjectCache.set(email, jiraUser.accountId);
16
17      console.log(`Found Jira User: ${jiraUser.accountId} (${jiraUser.displayName})`);
18      return jiraUser.accountId;
19    } else {
20      console.warn(`Jira User not found for email: ${email}`);
21      return "";
22    }
23  } catch (error) {
24    console.warn(`Error looking up Jira User: ${error.message}`);
25    return "";
26  }
27}

Usage in Update

javascript
1// In updateUser(), handle Type 2 attributes
2if (attrInfo.attributeType === 2) {
3  convertedValue = await this.lookupUserAccountId(change.newValue);
4  
5  // Skip User type attributes if lookup failed (user not found in Assets)
6  if (!convertedValue || convertedValue === "") {
7    console.log(`Skipping ${attrInfo.attributeName} - user not found in Assets`);
8    continue;
9  }
10}
11
12// Then use the accountId for update
13updatedAttributes.push({
14  objectTypeAttributeId: attrInfo.attributeId,
15  objectAttributeValues: [{ value: convertedValue }],
16});

Why This Matters

Different APIs with Different Rate Limits:

  • Microsoft Graph API uses OAuth with its own rate limits
  • Jira REST API has different rate limits than AQL-based Assets API
  • Caching Jira User lookups is critical to avoid hitting REST API rate limits

Solution 4: Data Preservation Strategy

Microsoft Graph is treated as the authority, but we should NEVER clear existing valid data from Assets. If Microsoft Graph doesn't have a value but the asset does, we MUST preserve the existing value.

Implementation Code

javascript
1detectChanges(graphUser, asset) {
2  const changes = [];
3
4  for (const [graphAttr, attrInfo] of Object.entries(this.attributeMapping)) {
5    let graphValue = graphUser[graphAttr];
6    const assetValue = this.getAttributeValue(asset, attrInfo.attributeName);
7
8    // CRITICAL: Preserve existing data if Graph has no value
9    if (
10      (graphValue === null ||
11        graphValue === undefined ||
12        graphValue === "") &&
13      assetValue !== null &&
14      assetValue !== undefined &&
15      assetValue !== ""
16    ) {
17      continue; // Skip this change - preserve existing data!
18    }
19
20    // Normalization and comparison logic
21    const normalizedGraphValue = this.normalizeValue(
22      graphValue,
23      attrInfo.attributeType
24    );
25    const normalizedAssetValue = this.normalizeValue(
26      assetValue,
27      attrInfo.attributeType
28    );
29
30    if (normalizedGraphValue !== normalizedAssetValue) {
31      changes.push({
32        attribute: attrInfo.attributeName,
33        oldValue: assetValue || "",
34        newValue: graphValue || "",
35        graphAttribute: graphAttr,
36        attributeType: attrInfo.attributeType,
37      });
38    }
39  }
40
41  return changes;
42}

Example Scenarios

Scenario 1: Preserve Company

  • Asset has: Company: "Example Company Inc."
  • Microsoft Graph has: companyName: ""
  • Result: No change detected, data preserved

Scenario 2: Update Empty Company

  • Asset has: Company: ""
  • Microsoft Graph has: companyName: "Example Company Inc."
  • Result: Change detected, will update

Scenario 3: Don't Clear Valid Company

  • Asset has: Company: "Example Company Inc."
  • Microsoft Graph has: companyName: ""
  • Result: No change detected, data preserved (NOT CLEARED!)

Solution 5: Error Handling & Fallback Mechanism

When updating assets, we might encounter errors like business rule restrictions or validation errors. The fallback mechanism removes failing attributes and retries with remaining ones.

Complete Implementation

javascript
1async updateUser(asset, graphUser, changes) {
2  console.log(`Updating asset ${asset.objectKey || asset.id}`);
3
4  // Fetch existing object's current attributes to preserve them
5  let existingAttributes = {};
6  try {
7    const existingObj = await this.cloudApiClient.getObject(asset.id);
8    if (existingObj && existingObj.attributes) {
9      for (const attr of existingObj.attributes) {
10        existingAttributes[attr.objectTypeAttributeId] = attr;
11      }
12    }
13  } catch (error) {
14    console.warn(`Warning: Could not fetch existing attributes: ${error.message}`);
15  }
16
17  // Build attributes to update - merge new values with existing ones
18  const updatedAttributes = [];
19
20  // First, copy all existing attributes to preserve them
21  for (const [attrId, attrValue] of Object.entries(existingAttributes)) {
22    updatedAttributes.push({
23      objectTypeAttributeId: parseInt(attrId),
24      objectAttributeValues: attrValue.objectAttributeValues,
25    });
26  }
27
28  const failedAttributes = [];
29
30  // Then, update with new values for changed attributes
31  for (const change of changes) {
32    const attrInfo = this.attributeMapping[change.graphAttribute];
33    if (attrInfo) {
34      let convertedValue = this.convertValue(
35        change.newValue,
36        attrInfo.attributeType,
37      );
38
39      // Handle Object type attributes (like Department, License, Location, Company)
40      if (attrInfo.attributeType === 1) {
41        convertedValue = await this.lookupObjectId(
42          attrInfo.attributeName,
43          change.newValue,
44        );
45        // Skip Object type attributes if lookup failed
46        if (!convertedValue || convertedValue === "") {
47          console.log(`Skipping ${attrInfo.attributeName} - referenced object not found in Assets`);
48          continue;
49        }
50      }
51
52      // Handle User type attributes (like "Jira user")
53      if (attrInfo.attributeType === 2) {
54        convertedValue = await this.lookupUserAccountId(change.newValue);
55        // Skip User type attributes if lookup failed
56        if (!convertedValue || convertedValue === "") {
57          console.log(`Skipping ${attrInfo.attributeName} - user not found in Assets`);
58          continue;
59        }
60      }
61
62      // Update or add the attribute
63      const attrIndex = updatedAttributes.findIndex(
64        (a) => a.objectTypeAttributeId === attrInfo.attributeId,
65      );
66
67      if (attrIndex >= 0) {
68        // Update existing attribute
69        updatedAttributes[attrIndex].objectAttributeValues = [
70          { value: convertedValue },
71        ];
72      } else {
73        // Add new attribute
74        updatedAttributes.push({
75          objectTypeAttributeId: attrInfo.attributeId,
76          objectAttributeValues: [{ value: convertedValue }],
77        });
78      }
79    }
80  }
81
82  const objectData = {
83    objectTypeId: this.options.objectTypeId,
84    attributes: updatedAttributes,
85  };
86
87  if (this.options.debug) {
88    console.log("DEBUG: Sending to updateObject:");
89    console.log(` objectId: ${asset.id}`);
90    console.log(` objectTypeId: ${objectData.objectTypeId}`);
91    console.log(" attributes:");
92    updatedAttributes.forEach((attr) => {
93      console.log(` ${attr.objectTypeAttributeId}: ${JSON.stringify(attr.objectAttributeValues[0].value)}`);
94    });
95  }
96
97  // Keep trying until success or no more attributes to update
98  while (updatedAttributes.length > 0) {
99    try {
100      const result = await this.cloudApiClient.updateObject(
101        asset.id,
102        objectData,
103      );
104
105      if (result) {
106        console.log(`Updated successfully (${result.objectKey || result.id})`);
107
108        // Log failed attributes if any
109        if (failedAttributes.length > 0) {
110          console.log(` ${failedAttributes.length} attribute(s) skipped due to errors:`);
111          failedAttributes.forEach((failed) => {
112            console.log(` - ${failed.attributeName}: ${failed.reason}`);
113          });
114
115          // Add to global error list for reporting
116          this.errors.push({
117            type: "attribute_update_failed",
118            user: asset.label || asset.objectKey,
119            userId: asset.id,
120            failedAttributes: failedAttributes,
121          });
122        }
123
124        return result;
125      }
126    } catch (error) {
127      // Try to identify which attribute caused the error
128      let failedAttrId = null;
129      let failedAttrName = "unknown";
130      let failureReason = error.message || "Unknown error";
131
132      if (error.response) {
133        let errorObj = error.response;
134
135        // Try to parse JSON response
136        if (typeof error.response === "string") {
137          try {
138            errorObj = JSON.parse(error.response);
139          } catch (e) {
140            errorObj = error.response;
141          }
142        }
143
144        // Look for errors object in parsed JSON
145        const errorsObj = errorObj.errors || errorObj;
146
147        if (typeof errorsObj === "object" && errorsObj !== null) {
148          // Iterate through error keys to find attribute restriction errors
149          for (const [key, value] of Object.entries(errorsObj)) {
150            const attrMatch = key.match(/^rlabs-insight-attribute-(\d+)$/);
151            if (attrMatch && attrMatch[1]) {
152              failedAttrId = parseInt(attrMatch[1]);
153              failureReason = value || "Invalid due to restrictions";
154              break;
155            }
156          }
157        }
158      }
159
160      // Find the corresponding change
161      const failedChange = changes.find((c) => {
162        const attrInfo = this.attributeMapping[c.graphAttribute];
163        return attrInfo && attrInfo.attributeId === failedAttrId;
164      });
165
166      if (failedChange) {
167        console.log(`Failed to update ${failedChange.attributeName}: ${failureReason}`);
168        console.log(`Removing this attribute and retrying...`);
169
170        // Track the failed attribute
171        failedAttributes.push({
172          attributeId: failedAttrId,
173          attributeName: failedChange.attributeName,
174          reason: failureReason,
175          oldValue: failedChange.oldValue,
176          newValue: failedChange.newValue,
177        });
178
179        // Remove this attribute from update
180        const attrIndex = updatedAttributes.findIndex(
181          (a) => a.objectTypeAttributeId === failedAttrId,
182        );
183        if (attrIndex >= 0) {
184          updatedAttributes.splice(attrIndex, 1);
185        }
186
187        // Remove this change
188        const changeIndex = changes.indexOf(failedChange);
189        if (changeIndex >= 0) {
190          changes.splice(changeIndex, 1);
191        }
192
193        // Rebuild objectData with remaining attributes
194        objectData.attributes = updatedAttributes;
195
196        // Try again with remaining attributes
197        continue;
198      } else {
199        // If we can't identify the failing attribute, log full error
200        console.error(`Could not identify which attribute caused the error. Full error: ${error.message}`);
201        console.error(`Error response: ${error.response || "No response"}`);
202        throw error;
203      }
204    }
205  }
206
207  throw new Error(
208    `Failed to update all attributes for ${asset.objectKey || asset.id}. See logs for details.`
209  );
210}

Error Response Parsing

The code handles both string and object error responses:

javascript
1// If error.response is a JSON string
2if (typeof error.response === "string") {
3  try {
4    errorObj = JSON.parse(error.response);
5  } catch (e) {
6    errorObj = error.response;
7  }
8}
9
10// Parse errors object
11const errorsObj = errorObj.errors || errorObj;
12
13// Iterate through error keys to find attribute restriction errors
14for (const [key, value] of Object.entries(errorsObj)) {
15  const attrMatch = key.match(/^rlabs-insight-attribute-(\d+)$/);
16  if (attrMatch && attrMatch[1]) {
17    failedAttrId = parseInt(attrMatch[1]);
18    failureReason = value || "Invalid due to restrictions";
19  }
20}
21

How the Fallback Works

  1. First Attempt - Try to update all attributes
  2. Error Encountered - API returns validation error for attribute 1486 (Company)
  3. Parse Error - Extract attribute ID from "rlabs-insight-attribute-1486"
  4. Identify Failed Change - Find the change that maps to attribute 1486
  5. Remove & Retry - Remove failing attribute from update, rebuild objectData
  6. Second Attempt - Try update again with remaining attributes
  7. Repeat Until Success - Keep removing failing attributes until success or none left to update
  8. Log Failures - Track all failed attributes in error array for manual fix

Complete Implementation Steps

Step 1: Set Up Environment Variables

Create a .env file in your project root:

bash
1# Microsoft Graph API Credentials
2MS_CLIENT_ID=your-client-id
3MS_TENANT_ID=your-tenant-id
4MS_CLIENT_SECRET=your-client-secret
5
6# Jira Cloud Assets Credentials
7WORKSPACE_ID=your-workspace-id
8CLOUD_API_TOKEN=your-api-token
9CLOUD_BASE_URL=https://api.atlassian.com
10
11# Optional Configuration
12OBJECT_SCHEMA_ID=15
13OBJECT_TYPE_ID=153

Step 2: Initialize Attribute Mapping

javascript
1const attributes = await this.cloudApiClient.getObjectTypeAttributes(
2  this.options.objectTypeId
3);
4
5const mapping = {};
6for (const attr of attributes) {
7  const graphAttr = Object.keys(DEFAULT_MAPPING).find(
8    key => DEFAULT_MAPPING[key] === attr.name
9  );
10  if (graphAttr) {
11    mapping[graphAttr] = {
12      attributeName: attr.name,
13      attributeId: attr.id,
14      attributeType: attr.type,    // Type codes: 0=Text, 1=Object, 2=User
15    };
16  }
17}
18
19this.attributeMapping = mapping;

Step 3: Query Existing Users

javascript
1const aqlQuery = `objectType = ${this.options.objectTypeId}`;
2
3const response = await this.cloudApiClient.executeAQL(
4  aqlQuery,
5  0,
6  500,    // Batch fetch all existing users
7  true
8);
9
10// Build ID-to-name mapping cache from first sample entry
11if (response.objectEntries && response.objectEntries.length > 0) {
12  const sampleEntry = response.objectEntries[0];
13
14  // Build mapping for attribute lookups
15  for (const attr of sampleEntry.attributes) {
16    this.attributeIdToNameMap.set(attr.objectTypeAttributeId, attr.name);
17    this.attributeIdToTypeInfoMap.set(attr.objectTypeAttributeId, {
18      name: attr.name,
19      type: attr.type,
20    });
21  }
22
23  // Build user lookup map
24  for (const entry of response.objectEntries) {
25    if (entry.attributes) {
26      const nameAttr = entry.attributes.find(
27        a => a.objectTypeAttributeId === 1478
28      );
29      if (nameAttr && nameAttr.objectAttributeValues[0]) {
30        const name = nameAttr.objectAttributeValues[0].value;
31        if (name) {
32          this.existingUsersMap.set(this.normalizeKey(name), entry);
33        }
34      }
35    }
36  }
37}
38

Step 4: Fetch Users from Microsoft Graph

javascript
1const users = await this.graphApiClient.fetchUsers({
2  filter: "userType eq 'Member'",
3  select: Object.keys(ATTRIBUTE_MAPPING).join(","),
4  maxResults: this.options.limit || 0,
5  expandManager: true,    // Expand to get manager information
6});
7

Step 5: Process Each User

javascript
1for (let i = 0; i < users.length; i++) {
2  const user = users[i];
3  const displayName = user.displayName || user.id || "Unknown";
4  const mail = user.mail || "";
5  const userPrincipalName = user.userPrincipalName || "";
6  const managerInfo = user.manager
7    ? `${user.manager.displayName} (${user.manager.mail || ""})`
8    : "None";
9
10  console.log(`[${i + 1}/${users.length}] Processing: ${displayName}`);
11  console.log(` Email: ${mail || "N/A"}`);
12  console.log(` UPN: ${userPrincipalName}`);
13  console.log(` Manager: ${managerInfo}`);
14
15  // Try to find matching existing user
16  const existingAsset = await this.findMatchingUser(user);
17
18  if (existingAsset) {
19    this.stats.existingUsersMatched++;
20
21    // Compare attributes to detect changes
22    const changes = this.detectChanges(user, existingAsset);
23
24    if (changes.length === 0) {
25      console.log(`MATCHED: No changes detected`);
26      this.stats.usersSkipped++;
27    } else {
28      console.log(`MATCHED: ${changes.length} change(s) detected`);
29      changes.forEach((change) => {
30        let changeMessage = ` - ${change.attribute}: "${change.oldValue}" → "${change.newValue}"`;
31        
32        // Add note for object reference attributes
33        if (change.attributeType === 1) {
34          changeMessage += ` (will look up object by name and use its ID)`;
35        }
36        
37        console.log(changeMessage);
38      });
39
40      if (!this.options.dryRun) {
41        await this.updateUser(existingAsset, user, changes);
42        this.stats.existingUsersUpdated++;
43      } else {
44        console.log(` [DRY RUN] Would update asset ${existingAsset.objectKey || existingAsset.id}`);
45        this.stats.usersSkipped++;
46      }
47    }
48  } else {
49    console.log(`NEW: Creating as new asset`);
50    
51    if (!this.options.dryRun) {
52      await this.createUser(user);
53      this.stats.newUsersCreated++;
54    } else {
55      console.log(` [DRY RUN] Would create new asset`);
56      this.stats.usersSkipped++;
57    }
58  }
59}

Step 6: Save Report

javascript
1saveReport() {
2  const logsDir = path.join(__dirname, "..", "logs");
3  if (!fs.existsSync(logsDir)) {
4    fs.mkdirSync(logsDir, { recursive: true });
5  }
6
7  const timestamp = new Date().toISOString().replace(/[:.]/g, "-");
8  const reportPath = path.join(logsDir, `ingestion-report-${timestamp}.json`);
9
10  const report = {
11    timestamp: new Date().toISOString(),
12    options: this.options,
13    duration: this.stats.endTime - this.stats.startTime,
14    durationString: this.formatDuration(this.stats.endTime - this.stats.startTime),
15    stats: this.stats,
16    graphApiStats: this.graphApiClient.getStats(),
17    cloudApiStats: this.cloudApiClient.getStats(),
18    errors: this.errors,    // Include all failed attributes for manual fix
19  };
20
21  fs.writeFileSync(reportPath, JSON.stringify(report, null, 2));
22  console.log(`Report saved to: ${reportPath}`);
23}

Best Practices

1. Always Use Caching

Cache all potential object matches, not just the first one. This enables fallback when business rules restrict certain objects.

2. Data Preservation is Critical

Never clear existing valid data from Assets. Only update when Microsoft Graph has a value and asset is empty.

3. Handle Rate Limits

Implement retry logic with exponential backoff for API calls. Jira REST API has different rate limits than AQL-based Assets API.

4. Comprehensive Error Logging

Track all failures in detailed error array with attribute IDs, names, reasons, and values. This enables manual review and fixes.

5. Test with Small Limits

Use --limit N flag to test with small batches before running full ingestion.

6. Use Dry-Run First

Always run --dry-run before actual ingestion to verify changes.

7. Monitor API Statistics

Track request counts and error rates to identify issues early.

Summary

This tutorial provides a production-tested solution for ingesting Microsoft Graph users into Jira Cloud Assets. The key learnings are:

Handle Multiple Attribute Types Correctly - Text (Type 0), Object References (Type 1), Users (Type 2)

Implement ID-to-Name Mapping - Enable attribute lookups by name instead of ID

Return Correct Values for Operations - displayValue for comparison, object ID for updates

Preserve Existing Data - Never clear valid data when Microsoft Graph is empty

Implement Fallback Mechanism - Handle business rule restrictions gracefully by removing failing fields and retrying

Log All Errors for Manual Fix - Track what couldn't be automated

By following this guide, you can build a robust ingestion system that handles complexities of Jira Assets API without relying on incomplete public documentation.

ShareXLinkedIn

Tags

microsoft-graphjirajira assetsjira cmdb

Comments

0

Add a comment

Confirm your address using the email we send. You can unsubscribe at any time. Your email stays private and this does not sign you up for the newsletter.